﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Management;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using Tools.constant;

namespace Tools
{
    public class SystemInfo
    {
        [DllImport("kernel32")]
        public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
        [DllImport("kernel32")]
        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
        [DllImport("kernel32")]
        private static extern void GlobalMemoryStatus(ref StorageInfo memibfo);
        [DllImport("kernel32")]
        public static extern void GetSystemInfo(ref CPUInfo cpuinfo);
        [DllImport("kernel32")]
        public static extern void GetSystemTime(ref SystemTimeInfo stinfo);
        [DllImport("Iphlpapi.dll")]
        public static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
        [DllImport("Ws2_32.dll")]
        public static extern Int32 inet_addr(string ipaddr);

        //内存信息结构体
        [StructLayout(LayoutKind.Sequential)]
        public struct StorageInfo //此处全是以字节为单位
        {
            public uint dwLength;//长度
            public uint dwMemoryLoad;//内存使用率
            public uint dwTotalPhys;//总物理内存
            public uint dwAvailPhys;//可用物理内存
            public uint dwTotalPageFile;//交换文件总大小
            public uint dwAvailPageFile;//可用交换文件大小
            public uint dwTotalVirtual;//总虚拟内存
            public uint dwAvailVirtual;//可用虚拟内存大小
        }
        /// <summary>
        /// 获取杀毒软件信息
        /// </summary>
        /// <returns></returns>
        public static AntiVirus GetVirus()
        {
            AntiVirus antiVirus = AntiVirus.UNKNOW;
            string myvirus = "";
            try
            {
                WqlObjectQuery wqlQuery = new WqlObjectQuery("SELECT * FROM AntiVirusProduct");
                string computer = Environment.MachineName;
                string path = @"\\" + computer + @"\root\SecurityCenter2";

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(path, "SELECT * FROM AntiVirusProduct");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    String name = queryObj["displayName"].ToString();
                    if (name != "")
                    {
                        myvirus += name + "\n\r";
                        foreach (AntiVirus virus in Enum.GetValues(typeof(AntiVirus)))
                        {
                            if (name.ToUpper().Contains(virus.ToString()) || name.Contains(EnumHelper.GetDescription(virus)))
                            {
                                antiVirus = virus;
                                break;
                            }
                        }
                    }
                    if (!name.Contains("Window"))
                    {
                        if (queryObj["companyName"] != null)
                        {
                            myvirus += "您正在使用" + queryObj["companyName"].ToString() + "的杀毒软件\n\r";
                        }
                        if (queryObj["versionNumber"] != null)
                        {
                            myvirus += "版本号：" + queryObj["versionNumber"].ToString() + "\n\r";
                        }
                    }
                }

            }
            catch
            {
                myvirus = "error";
            }
            //MessageBox.Show(myvirus);
            return antiVirus;
        }

        /// <summary>
        /// 检测杀毒软件 -- 从进程
        /// </summary>
        public static List<AntiVirus> GetKavass()
        {
            List<AntiVirus> antiVirus = new List<AntiVirus>();
            String pNames = "";
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                //txt += p.ProcessName + "\r\n";
                foreach (var key in SysConstant.VirusMap.Keys)
                {
                    String process = "|" + SysConstant.VirusMap[key].ToString().ToLower() + "|";//  |a|bc|d|ef|
                    if (process.Contains("|" + p.ProcessName.ToLower() + "|"))
                    {
                        AntiVirus virus = (AntiVirus)key;
                        if (!antiVirus.Contains(virus))
                        {
                            antiVirus.Add(virus);
                            pNames += p.ProcessName + "，";
                        }
                    }
                }
            }
            //LogHelper.SaveLog("系统所有进程：", txt);
            if (antiVirus.Count > 0)
            {
                LogHelper.SaveLog("检测杀毒软件", "杀毒软件进程：" + pNames + "，类型：" + GetViruNames(antiVirus));
            }
            return antiVirus;
        }

        /// <summary>
        /// 获取枚举Description Attribute的值
        /// </summary>
        /// <param name="value">枚举</param>
        /// <returns></returns>
        public static string GetViruNames(List<AntiVirus> values)
        {
            if (values.Count == 0)
                return "";

            String op = "";
            String result = "";
            foreach (var item in values)
            {
                result += op + EnumHelper.GetDescription(item);
                op = "，";
            }
            return result;
        }

        //cpu信息结构体
        [StructLayout(LayoutKind.Sequential)]
        public struct CPUInfo
        {
            public uint cpu的OemId;
            public uint cpu页面大小;
            public uint lpMinimumApplicationAddress;
            public uint lpMaximumApplicationAddress;
            public uint dwActiveProcessorMask;
            public uint cpu个数;
            public uint cpu类别;
            public uint dwAllocationGranularity;
            public uint cpu等级;
            public uint cpu修正;
        }
        //系统时间信息结构体
        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTimeInfo
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }
        //获取内存信息
        public static StorageInfo GetStorageInfo()
        {
            StorageInfo memInfor = new StorageInfo();
            GlobalMemoryStatus(ref memInfor);
            return memInfor;
        }
        //获取cpu信息
        public static CPUInfo GetCPUInfo()
        {
            CPUInfo memInfor = new CPUInfo();
            GetSystemInfo(ref memInfor);
            return memInfor;
        }
        //获取系统时间信息
        public static SystemTimeInfo GetSystemTimeInfo()
        {
            SystemTimeInfo memInfor = new SystemTimeInfo();
            GetSystemTime(ref memInfor);
            return memInfor;
        }
        //获取内存利用率函数
        public static string Getutilization_rate()
        {
            StorageInfo memInfor = new StorageInfo();
            GlobalMemoryStatus(ref memInfor);
            return memInfor.dwMemoryLoad.ToString("0.0");
        }
        //获取系统路径
        public static string Getsystem_path()
        {
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            GetSystemDirectory(Buff, nChars);
            return Buff.ToString();
        }
        //获取window路径
        public static string Getwindow_path()
        {
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            GetWindowsDirectory(Buff, nChars);
            return Buff.ToString();
        }
        //获取cpu的id号
        public static string GetCPUID()
        {
            try
            {
                string cpuInfo = "";//cpu序列号 
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
        }
        //获取设备硬件卷号
        public static string GetDisk_VolumeSerialNumber()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"d:\"");
            disk.Get();
            return disk.GetPropertyValue("VolumeSerialNumber").ToString();
        }
        //获取mac地址
        public static string Getmac_address()
        {
            string mac = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    mac = mo["MacAddress"].ToString();
                }
                mo.Dispose();
            }
            return mac;
        }
        //根据ip获取邻节点MAC地址
        public static string Getremote_mac(string ip)
        {
            StringBuilder mac = new StringBuilder();
            try
            {
                Int32 remote = inet_addr(ip);
                Int64 macinfo = new Int64();
                Int32 length = 6;
                SendARP(remote, 0, ref macinfo, ref length);
                string temp = Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                        mac.Append(temp.Substring(x - 2, 2));
                    else
                        mac.Append(temp.Substring(x - 2, 2) + "-");
                    x -= 2;
                }
                return mac.ToString();
            }
            catch
            {
                return mac.ToString();
            }
        }
        //获取本机的ip地址
        public static string Getip()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString(); 
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        //获取硬盘id号
        public static string Getdisk_id()
        {
            try
            {
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
        }
        //获得系统登陆用户名
        public static string Getuser()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["UserName"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        //获得系统类型
        public static string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["SystemType"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        //获得物理总内存
        public static string GetTotalPhysicalMemory()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["TotalPhysicalMemory"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        //获得电脑名称
        public static string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch
            {
                return "unknow";
            }
        }
        //获取os版本信息
        public static OsVer GetOSVersion()
        {
            OsVer osVer = OsVer.UNKNOW;
            String osStr = "";

            System.OperatingSystem version = System.Environment.OSVersion;

            if (version.Platform.Equals(System.PlatformID.Win32Windows))
            {
                switch (version.Version.Minor)
                {
                    case 0:
                        osStr = "Windows 95";
                        break;
                    case 10:
                        if (version.Version.Revision.ToString() == "2222A")
                            osStr = "Windows 98 Second Edition";
                        else
                            osStr = "Windows 98";
                        break;
                    case 90:
                        osStr = "Windows Me";
                        break;
                }
            }
            if (version.Platform.Equals(System.PlatformID.Win32NT))
            {
                switch (version.Version.Major)
                {
                    case 3:
                        osStr = "Windows NT 3.51";
                        break;
                    case 4:
                        osStr = "Windows NT 4.0";
                        break;
                    case 5:
                        if (version.Version.Minor == 0)
                            osStr = "Windows 2000";
                        else
                        {
                            osStr = "Windows XP";
                            if (version.VersionString.Contains("Service Pack 1"))
                            {
                                osVer = OsVer.WINXP1;
                            }
                            else if (version.VersionString.Contains("Service Pack 2"))
                            {
                                osVer = OsVer.WINXP2;
                            }
                            else if (version.VersionString.Contains("Service Pack 3"))
                            {
                                osVer = OsVer.WINXP3;
                            }
                        }
                        break;
                    case 6:
                        {
                            if (version.Version.Minor.Equals(1))
                            {
                                osStr = "Windows 7";
                                osVer = OsVer.WIN7;
                            }
                            else if (version.Version.Minor.Equals(2))
                            {
                                osStr = "Windows 8";
                                osVer = OsVer.WIN8;
                            }
                            else if (version.Version.Minor.Equals(3))
                            {
                                osStr = "Windows 8.1";
                                osVer = OsVer.WIN8_1;
                            }
                        }
                        break;
                    case 10:
                        {
                            osStr = "Windows 10";
                            osVer = OsVer.WIN10;
                        }
                        break;
                }
            }

            int build = version.Version.Build;
            String versionStr = version.VersionString;

            //LogHelper.SaveLog("操作系统版本：", "builder=" + build + ",versionStr=" + versionStr + "");
            osStr = "发现失败";

            return osVer;
        }
    }

}
